package com.min.log

import javassist.ClassPool
import javassist.CtClass
import javassist.CtMethod

class ClickInject {

    static void inject(File classFile, String path) {
        ClassPool pool = ClassPool.getDefault()
        try {
            //截取当前类的路径，+8为classes+.的长度,再取出后边的.class的6位
            def packagePath = classFile.absolutePath.substring(classFile.absolutePath.lastIndexOf("classes") + 8, classFile.absolutePath.length() - 6)
            def replacePath = packagePath.replaceAll("/", ".")
            println(replacePath)
            CtClass operationClass  = pool.get(replacePath)
            CtMethod method = operationClass.getDeclaredMethod("onClick")
            method.insertAfter("System.out.println(\"click success\");")
            operationClass.writeFile(path)
            operationClass.detach()
        } catch (Exception e) {
            e.printStackTrace()
            println("当前类不是clickListener的实现类")
        }
    }
}